import { observer, useLocalObservable } from 'mobx-react'
import styles from './index.module.less'
import Store from '../store'
import RainbowChart from '@/components/RainbowChart'
import BtnBotLayout from '@/components/BtnBotLayout'
import { history, useLocation, useParams } from 'umi'
import { useEffect, useRef, useState } from 'react'
import { Dialog, Image, ImageViewer, Toast } from 'antd-mobile'
import { getData, putData } from '@/servers/http'
import { api } from '@/servers/api'
import wx from 'weixin-webview-jssdk'
import { getLocalStorage } from '@/storage'
import GenerateRainbow from '@/components/GenerateRainbow'

export default observer(() => {
    const identityType = getLocalStorage('IDENTITY_TYPE')
    const store = useLocalObservable(() => Store())
    const { isFinished, isEdit, setIsEdit, barriersInfo } = store
    const generateRef = useRef<any>()
    const chartRef = useRef<any>()
    // 是否是新的生涯彩虹图
    const [isNew, setIsNew] = useState(false)
    const [newImg, setNewImg] = useState()
    const [img, setImg] = useState<string>()
    const [visible, setVisible] = useState(false)
    const { id, medalData } = useParams<any>()
    const { from } = useLocation().query

    /** 展示弹窗 */
    const showSelectModal = () => {
        if (isFinished) {
            Dialog.confirm({
                content: '同步我的实训结果生成档案',
                cancelText: '取消',
                confirmText: '同步档案',
                onConfirm: () => {
                    putData(`${api.userBarriersBatchUpdate}${id}`, { fill_type: 3 }).then(({ status }) => {
                        if (status === 200) {
                            history.replace({
                                pathname: '/archivedetail',
                                query: { id },
                            })
                        }
                    })
                },
            })
        } else {
            Dialog.confirm({
                content: '已生成的我的求职档案',
                cancelText: '好的',
                confirmText: '前往档案',
                onConfirm: () => {
                    history.replace({
                        pathname: '/archivedetail',
                        query: { id },
                    })
                },
            })
        }
    }
    /** 校验是否需要展示弹窗 */
    const checkShow = () => {
        if (Number(identityType) === 2) {
            showSelectModal()
        } else {
            getData(api.userBarriersScoreInfo).then(res => {
                if (Number(res.data?.is_score) === 1) {
                    Toast.show(Number(res.data?.is_course_score) === 1 ? '讲师已评分' : '讲师已评审')
                    return
                } else {
                    showSelectModal()
                }
            })
        }
    }
    /** 判断是否是新的生涯彩虹图，是新的话创建新的图 */
    const judgeRainbow = () => {
        let flag = true
        barriersInfo.forEach(ele => {
            ele.settings?.forEach(item => {
                if (Number(item.grade) > 3) {
                    flag = false
                }
            })
        })
        setIsNew(flag)
        if (flag) {
            const imgUrl = generateRef.current?.exportImage(JSON.parse(JSON.stringify(barriersInfo)))
            setNewImg(imgUrl)
        }
    }

    useEffect(() => {
        document.title = '生涯彩虹图'
        if (Number(identityType) !== 2 && medalData) {
            wx.miniProgram.navigateTo({
                url: `/pageStudent/pages/gotMedal/index?medalData=${medalData}`,
            })
        }
        if (isEdit) {
            checkShow()
        }
        judgeRainbow()
        return () => {
            setIsEdit(false)
        }
    }, [])

    /** 图片预览 */
    const previewImage = (event: React.MouseEvent<HTMLImageElement, Event>) => {
        event.stopPropagation()
        ImageViewer.show({ image: newImg })
    }
    const handlePreview = async () => {
        if (!img) {
            Toast.show('正在生成预览...')
            const url: string = await chartRef?.current?.exportImg()
            setImg(url)
            Toast.clear()
        }
        setVisible(true)
    }

    return (
        <div className={styles.container}>
            <BtnBotLayout
                footer={
                    from !== 'archives' ? (
                        <div className={styles.options}>
                            <div
                                className={styles.white_btn}
                                onClick={() => {
                                    history.replace(`/rainbow/step1/${id}?id=${id}`)
                                }}
                            >
                                编辑
                            </div>
                        </div>
                    ) : null
                }
            >
                <div className={styles.form_wrapper}>
                    <div className={styles.title}>
                        <span className={styles.title_span}>我的生涯彩虹图</span>
                    </div>
                    {barriersInfo?.length && (
                        <div>
                            <div className={styles.rainbow_container} onClick={handlePreview}>
                                {isNew ? (
                                    <Image className={styles.image} src={newImg} onClick={previewImage} />
                                ) : (
                                    <RainbowChart data={barriersInfo} ref={chartRef} width={(343 / 375) * window.innerWidth} />
                                )}
                            </div>
                            {barriersInfo?.map((item: any, index: number) => {
                                return (
                                    <div className={styles.block_title} key={item?.id || index}>
                                        <span>
                                            角色{index + 1}：{item?.name}
                                        </span>
                                        <span>
                                            时间广度：{item?.age_start}岁~
                                            {item?.age_end}岁
                                        </span>
                                    </div>
                                )
                            })}
                        </div>
                    )}
                </div>
            </BtnBotLayout>
            <GenerateRainbow ref={generateRef} />
            <ImageViewer
                image={img}
                visible={visible}
                onClose={() => {
                    setVisible(false)
                }}
            />
        </div>
    )
})

document.title = '生涯彩虹图'
